package business;

import persistence.Role;
import persistence.RoleDAO;
import persistence.User;
import persistence.UserDAO;
import persistence.exception.DAOException;
import business.exception.BusinessException;

public class UserManagerImpl implements UserManager {
	
	//TODO: USE INTERFACE UserProvider that fetches UserInformation (implementations: f.e. Tomcat Realm, JaaS, ...)
	private UserDAO userDAO;
	private RoleDAO roleDAO;
	
	@Override
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	@Override
	public UserDAO getUserDAO() {
		return userDAO;
	}

	@Override
	public void setRoleDAO(RoleDAO roleDAO) {
		this.roleDAO = roleDAO;		
	}

	@Override
	public RoleDAO getRoleDAO() {
		return roleDAO;
	}
	
	@Override
	public void addUser(User u) throws BusinessException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void updateUser(User u) throws BusinessException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public User getUserForCredentials(String username, String password)
			throws BusinessException {
		User user = null;
		try {
			//TODO: encrypt user password to match MD5-Hash stored in DB
			user = userDAO.findByUsernameAndEncryptedPassword(username, password);
		}
		catch (DAOException de) {
			throw new BusinessException("Problem when attempting to find User with username " + username + " and password " + password, de);
		}
		return user;
	}

	@Override
	public void logout(User u) throws BusinessException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void resetPasswordForUser(User u) throws BusinessException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Boolean userIsInRole(User user, Role role) throws BusinessException {
		Boolean retVal = Boolean.FALSE;	
		if (user != null) {
			if (user.getRoles() != null) {
				for (Role r : user.getRoles()) {
					if (r.equals(role)) {
						retVal = Boolean.TRUE;
					}
				}
			}
		}
		return retVal;
	}

	@Override
	public Boolean isAdmin(User user) throws BusinessException {
		if (user != null) {
			for (Role role : user.getRoles()) {
				if (role.getName().equals(ADMIN_ROLE)) {
					return Boolean.TRUE;
				}
			}
		}
		return Boolean.FALSE;
	}
}
